// pages/share_goods/share_goods.js
var common = require("../../common/common.js").common;

Page({
    /**
   * 页面的初始数据
   */
    data: {
        color_header: "#fff",
        color_text: "white",
        color_main: "",
        color_minor: "",
        canvaHeight: 0,
        product: [],
        Qc: "",
        leader_info: [],
        apptitle: ""
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.showLoading({
            title: "图片生成中"
        });
        this.getBase();
        this.getData();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title
                });
            }
        });
    },
    canvas: function() {
        var rpx;
        var that = this;
        let proimg;
        wx.getSystemInfo({
            success: function(res) {
                rpx = res.windowWidth / 375;
            }
        });
        var logoImg = "/images/share_logo.png";
        const ctx = wx.createCanvasContext("myCanvas");
        //大背景
                var color_main = that.data.color_main;
        ctx.setFillStyle(color_main);
        ctx.fillRect(0, 0, 355 * rpx, (5 * 72 + 20) * rpx + 90 * rpx + 105 * rpx + 50 * rpx);
        //竖线
                ctx.setFillStyle("#ffffff");
        ctx.fillRect(178 * rpx, 1 * rpx, 1 * rpx, 50 * rpx);
        //头部
                ctx.beginPath();
        ctx.arc(179 * rpx, 180 * rpx, 150 * rpx, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = "#ffffff";
        ctx.fill();
        //小圆点
                ctx.beginPath();
        ctx.arc(178 * rpx, 38 * rpx, 4 * rpx, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = "#47B34F";
        ctx.fill();
        //标题1
                let now = new Date();
        let month = now.getMonth() + 1;
        let day = now.getDate();
        let str1 = month + "月" + day + "日爆款推荐";
        ctx.setFillStyle("#434343");
        ctx.font = "15px bold";
        ctx.fillText(str1, 112 * rpx, 64 * rpx);
        //标题2
                let str2 = "嗨购全场";
        ctx.setFillStyle("#434343");
        ctx.font = "11px bold";
        ctx.fillText(str2, 154 * rpx, 80 * rpx);
        //商品信息框
                ctx.setFillStyle("#ffffff");
        ctx.fillRect(20 * rpx, 90 * rpx, 315 * rpx, (5 * 72 + 20) * rpx);
        //商品
                let goodsImage = "/images/share.jpg";
        let goodsTitle = "商品名称商品名称商品名称";
        let goodsPrice = "￥98";
        let product = that.data.product;
        for (var i = 0; i < product.length; i++) {
            let index = Math.floor(i / 2);
            if (product[i].img.indexOf("https") == -1) {
                proimg = "https://" + product[i].img.substring(7);
            } else {
                proimg = product[i].img;
            }
            if (i % 2 == 0) {
                //商品图片
                wx.getImageInfo({
                    src: proimg,
                    success: res => {
                        ctx.drawImage(res.path, 45 * rpx, (110 + 72 * index) * rpx, 56 * rpx, 56 * rpx);
                    }
                });
                //商品标题
                                ctx.setFillStyle("#434343");
                ctx.font = "12px normal";
                that.textLine(ctx, product[i].name, 110 * rpx, (120 + 72 * index) * rpx, 60 * rpx);
                //商品价格
                                ctx.setFillStyle("#fe3112");
                ctx.font = "15px normal";
                ctx.fillText(product[i].price, 110 * rpx, (165 + 72 * index) * rpx);
            } else {
                //商品图片
                if (product[i].img.indexOf("https") == -1) {
                    proimg = "https://" + product[i].img.substring(7);
                } else {
                    proimg = product[i].img;
                }
                wx.getImageInfo({
                    src: proimg,
                    success: res => {
                        ctx.drawImage(res.path, 191 * rpx, (110 + 72 * index) * rpx, 56 * rpx, 56 * rpx);
                    }
                });
                //商品标题
                                ctx.setFillStyle("#434343");
                ctx.font = "12px normal";
                that.textLine(ctx, product[i].name, 255 * rpx, (120 + 72 * index) * rpx, 60 * rpx);
                //商品价格
                                ctx.setFillStyle("#fe3112");
                ctx.font = "15px normal";
                ctx.fillText(product[i].price, 255 * rpx, (165 + 72 * index) * rpx);
            }
        }
        // //二维码信息
                ctx.setFillStyle("rgba(255,255,255,0.8)");
        ctx.fillRect(20 * rpx, (5 * 72 + 20) * rpx + 90 * rpx, 315 * rpx, 105 * rpx);
        if (that.data.leader_info.name) {
            //姓名
            var leader_info = that.data.leader_info;
            let name = "小区团长：" + leader_info.name;
            ctx.setFillStyle("#434343");
            ctx.font = "12px normal";
            ctx.fillText(name, 45 * rpx, (20 + 72 * 5 + 90 + 36) * rpx);
            //小区名称
                        let time = "小区名称：" + leader_info.title;
            ctx.setFillStyle("#434343");
            ctx.font = "12px normal";
            that.textLine2(ctx, time, 45 * rpx, (20 + 72 * 5 + 90 + 57) * rpx, 170 * rpx);
            //提货地址
                        let address = "提货地址：" + leader_info.other;
            ctx.setFillStyle("#434343");
            ctx.font = "12px normal";
            that.textLine(ctx, address, 45 * rpx, (20 + 72 * 5 + 90 + 78) * rpx, 190 * rpx);
        } else {
            var apptitle = that.data.apptitle;
            ctx.setFillStyle("#434343");
            ctx.font = "12px normal";
            that.textLine2(ctx, apptitle, 45 * rpx, (20 + 72 * 5 + 90 + 36) * rpx, 170 * rpx);
            //下方带边框矩形
                        ctx.setFillStyle("#ffffff");
            ctx.setStrokeStyle(color_main);
            ctx.strokeRect(45 * rpx, (20 + 72 * 5 + 90 + 50) * rpx, 124 * rpx, 34 * rpx);
            //矩形内文字
                        ctx.font = "14px bold";
            ctx.setFillStyle(color_main);
            ctx.fillText("长按二维码抢购", 55 * rpx, (20 + 72 * 5 + 90 + 72) * rpx);
        }
        //二维码
                let ewm = "";
        setTimeout(() => {
            wx.getImageInfo({
                src: that.data.Qc,
                success: res => {
                    ewm = res.path;
                    ctx.drawImage(ewm, 240 * rpx, (20 + 72 * 5 + 90 + 20) * rpx, 75 * rpx, 75 * rpx);
                    wx.hideLoading();
                    ctx.draw();
                }
            });
        }, 3e3);
        let canvaHeight = (5 * 144 + 40) * rpx + 180 * rpx + 210 * rpx + 100 * rpx;
        that.setData({
            canvaHeight: canvaHeight
        });
    },
    drawRoundRect: function(ctx, x, y, w, h, r) {
        if (w < 2 * r) {
            r = w / 2;
        }
        if (h < 2 * r) {
            r = h / 2;
        }
        //
                ctx.setFillStyle("#ffffff");
        //填充颜色
                ctx.setStrokeStyle("#ffffff");
        //边框颜色
                ctx.beginPath();
        ctx.moveTo(x + r, y);
        ctx.arcTo(x + w, y, x + w, y + h, r);
        ctx.arcTo(x + w, y + h, x, y + h, r);
        ctx.arcTo(x, y + h, x, y, r);
        ctx.arcTo(x, y, x + w, y, r);
        ctx.closePath();
        ctx.fill();
    },
    drawRoundRect2: function(ctx, x, y, w, h, r) {
        if (w < 2 * r) {
            r = w / 2;
        }
        if (h < 2 * r) {
            r = h / 2;
        }
        //
                ctx.setFillStyle("rgba(255,255,255,0.8)");
        //填充颜色
                ctx.setStrokeStyle("#ffffff");
        //边框颜色
                ctx.beginPath();
        ctx.moveTo(x + r, y);
        ctx.arcTo(x + w, y, x + w, y + h, r);
        ctx.arcTo(x + w, y + h, x, y + h, r);
        ctx.arcTo(x, y + h, x, y, r);
        ctx.arcTo(x, y, x + w, y, r);
        ctx.closePath();
        ctx.fill();
    },
    textLine2: function(ctx, text, x, y, maxWidth) {
        var chr = text.split("");
        //这个方法是将一个字符串分割成字符串数组
                var temp = "";
        var row = [];
        for (var c = 0; c < chr.length; c++) {
            if (ctx.measureText(temp).width < maxWidth) {
                temp += chr[c];
            } else {
                c--;
                //这里添加了a-- 是为了防止字符丢失，效果图中有对比
                                row.push(temp);
                temp = "";
            }
        }
        row.push(temp);
        //如果数组长度大于2 则截取前两个
                if (row.length > 1) {
            var rowCut = row.slice(0, 1);
            var rowPart = rowCut[0];
            var test = "";
            var empty = [];
            for (var d = 0; d < rowPart.length; d++) {
                if (ctx.measureText(test).width < maxWidth) {
                    test += rowPart[d];
                } else {
                    break;
                }
            }
            empty.push(test);
            var group = empty[0] + "...";
            //这里只显示两行，超出的用...表示
                        rowCut.splice(0, 1, group);
            row = rowCut;
        }
        for (var f = 0; f < row.length; f++) {
            if (f == 0) {
                ctx.fillText(row[f], x, y);
            }
        }
    },
    textLine: function(ctx, text, x, y, maxWidth) {
        var chr = text.split("");
        //这个方法是将一个字符串分割成字符串数组
                var temp = "";
        var row = [];
        for (var c = 0; c < chr.length; c++) {
            if (ctx.measureText(temp).width < maxWidth) {
                temp += chr[c];
            } else {
                c--;
                //这里添加了a-- 是为了防止字符丢失，效果图中有对比
                                row.push(temp);
                temp = "";
            }
        }
        row.push(temp);
        //如果数组长度大于2 则截取前两个
                if (row.length > 2) {
            var rowCut = row.slice(0, 2);
            var rowPart = rowCut[1];
            var test = "";
            var empty = [];
            for (var d = 0; d < rowPart.length; d++) {
                if (ctx.measureText(test).width < maxWidth) {
                    test += rowPart[d];
                } else {
                    break;
                }
            }
            empty.push(test);
            var group = empty[0] + "...";
            //这里只显示两行，超出的用...表示
                        rowCut.splice(1, 1, group);
            row = rowCut;
        }
        for (var f = 0; f < row.length; f++) {
            if (f == 0) {
                ctx.fillText(row[f], x, y);
            } else {
                ctx.fillText(row[f], x, y + 20);
            }
        }
    },
    getData: function() {
        var that = this;
        common.request({
            endpoint: "share/index",
            method: "post",
            data: {
                page: "pages/index/index"
            },
            success: res => {
                var product = res.extra.product;
                that.setData({
                    leader_info: res.extra.leader_info,
                    product: product,
                    Qc: res.extra.Qc
                });
                that.canvas();
            }
        });
    },
    saveimgdo: function() {
        var that = this;
        wx.getSetting({
            success(res) {
                if (!res.authSetting["scope.writePhotosAlbum"]) {
                    wx.authorize({
                        scope: "scope.writePhotosAlbum",
                        success() {
                            that.dosave();
                        },
                        fail() {
                            wx.openSetting();
                            wx.showModal({
                                title: "提示",
                                content: "未授权相册，请删小程序后再试！"
                            });
                        }
                    });
                } else {
                    that.dosave();
                }
            }
        });
    },
    dosave: function() {
        var that = this;
        var pwidth = that.data.pwidth;
        var pheight = that.data.heigts;
        var pixelRatio = that.data.pixelRatio;
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: pwidth,
            height: pheight,
            destWidth: pwidth * pixelRatio,
            destHeight: pheight * pixelRatio,
            canvasId: "myCanvas",
            success: function(res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function(res) {
                        wx.showModal({
                            title: "提醒",
                            content: "请转发您分享图给好友吧！",
                            showCancel: false,
                            success: function(res) {
                                wx.navigateBack({
                                    delta: 1
                                });
                            }
                        });
                    },
                    fail: function(res) {}
                });
            }
        });
    }
});